{% extends "base.html" %}
{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

{% block title %}Record Emissions for Meter: {{ meter.meter_id }}{% endblock %}

{% block content %}
<div class="container">

  {% include "core/_breadcrumbs.html" %}

  <div class="card mb-3" id="createemissions">
    <div class="card-body">
      <h2>Record Emissions for Meter {% if meter.description %}{{ meter.description }}{% else %}{{ meter.meter_id }}{% endif %}</h2>
      <br/>
      {% block inner_content %}

      <div class="alert alert-danger mt-3" role="alert" v-if="errors.error">
          ${ errors.error }
      </div>
      <div class="alert alert-success mt-3" role="alert" v-if="successes.success" v-cloak>
        ${ successes.success }
      </div>

      <div class="form-group">
        <label for="fromDate">From Date*</label>
        <b-form-input type="text" class="datetime" id="fromDate" placeholder="Input Date" :state="fromDateState" v-model="fromDate" required></b-form-input>
        <b-form-invalid-feedback id="fromDate">
            From Date is required
        </b-form-invalid-feedback>
      </div>

      <div class="form-group">
        <label for="thruDate">Thru Date*</label>
        <b-form-input type="text" class="datetime" id="thruDate" placeholder="Input Date" :state="thruDateState" v-model="thruDate" required></b-form-input>
        <b-form-invalid-feedback id="thruDate">
            Thru Date is required
        </b-form-invalid-feedback>
      </div>

      <div class="form-group">
        <label for="document">Document</label>
        <input type="file" class="input-file" id="document" :state="documentState" v-model="document"></input>
      </div>

      <div class="mt-3 text-right">
        <b-button v-if="!isRecordDisabled && !success" variant="primary" v-on:click.stop.prevent="get_meter_total_energy_used()" :disabled="isRecordDisabled">
          Record
        </b-button>
        <b-button v-else-if="success && errors.error" variant="secondary" v-on:click.stop.prevent="get_meter_total_energy_used()" :disabled="!isRecordDisabled">
          Failed
        </b-button>
        <b-button v-else-if="success" variant="secondary" v-on:click.stop.prevent="get_meter_total_energy_used()" :disabled="!isRecordDisabled">
          Recorded
        </b-button>
        <b-button v-else variant="secondary" v-on:click.stop.prevent="get_meter_total_energy_used()" :disabled="isRecordDisabled">
          Please wait...
        </b-button>
        {% comment %} <b-spinner v-if="isRecordDisabled" variant="secondary"></b-spinner> {% endcomment %}
      </div>
      <a v-bind:href="url">
        <button class="btn btn-primary mt-5" type="submit">Back</button>
      </a>
     {% endblock inner_content %}

    </div>
  </div>
</div>
<script>
(function() {
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';

  new Vue({
    delimiters: ['${', '}'],
    name: 'createemissions',
    el: '#createemissions',
    data() {
      return {
        userId: "{{user.username}}",
        orgName: "{{user.org_name}}",
        csrfmiddlewaretoken: CSRF_TOKEN,
        isRecordDisabled: false,
        success: false,
        url: "/opentaps_seas/meter/view/{{ meter_id|safe}}",
        fromDateState: null,
        fromDate: moment().startOf('month').format('YYYY-MM-DD HH:mm:ss'),
        thruDateState: null,
        thruDate: moment().endOf('month').format('YYYY-MM-DD HH:mm:ss'),
        documentState: null,
        document: "",
        errors: {'error': null},
        successes:  {'success': null},
        meterId: {%if meter_id %}'{{ meter_id|safe}}'{%else%}''{%endif%},
        utilityId: {%if meter.utility_id %}'{{ meter.utility_id|safe}}'{%else%}''{%endif%},
        accountNumber: {%if meter.account_number %}'{{ meter.account_number|safe}}'{%else%}''{%endif%},

      }
    },
    mounted() {
      flatpickr(this.$el.getElementsByClassName('datetime'), {
          "dateFormat": "Y-m-d H:i:S",
          "time_24hr": "true",
          "allowInput": "true",
          "enableTime": "true",
          "enableSeconds": "true",
          "minuteIncrement": 1
        });
    },
    methods: {
      get_meter_total_energy_used() {
        this.errors = {'error': null};
        this.successes =  {'success': null};
        url = "/opentaps_seas/meter_history_json/total/" + this.meterId + '?from_date=' + this.fromDate + '&thru_date=' + this.thruDate;
        axios.get(url)
          .then(x => {

            if (x.data.error) {
                this.errors['error'] = x.data.error;
            } else if (!x.data.item) {
                this.errors['error'] = 'Cannot get meter total energy used.';
            } else {
                this.record_emissions(x.data.item)
            }
          })
          .catch(err => {
            e = getResponseError(err);
            this.errors = e;
            this.isRecordDisabled = false;
          });
      },
      record_emissions(item) {
        this.isRecordDisabled = true;
        let reader = new FileReader()
        let parent = this;
        reader.onload = function(e) {  
          let bfile = e.target.result
          url = "/opentaps_seas/emissions/record_emissions.json"
          data = new Object();
          data['user_id'] = parent.userId,
          data['org_name'] = parent.orgName,
          data['utility_id'] = parent.utilityId,
          data['account_number'] = parent.accountNumber,
          data['from_date'] = item.from_date,
          data['thru_date'] = item.thru_date,
          data['amount'] = item.total,
          data['uom'] = item.uom,
          data['document'] = bfile
          axios.post(url, data, {headers: {'X-CSRFToken': parent.csrfmiddlewaretoken}})
            .then(x => x.data)
            .then(x => {
              if (x.success) {
                parent.successes = {'success': 'Successfully created.'};

              } else if (x.error) {
                parent.errors['error'] = x.error;
              } else {
                parent.errors['error'] = 'Cannot record emissions';
              }
              parent.isRecordDisabled = false;
              parent.success = true;
            })
            .catch(err => {
              e = getResponseError(err);
              console.error(e, err);
              parent.errors = e;
              parent.isRecordDisabled = false;
            });
        }
        let file = document.getElementById("document").files[0]
        if (!file) file = new Blob()
        let test = reader.readAsDataURL(file)
      },
    }
  });
})();
</script>
{% endblock content %}